
package present;

import avenue.Session;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import model.DBManager;
import model.Payment;
import model.Station;
import model.Vehicle;

public class PresentPaymentForm extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public PresentPaymentForm() {
      em = DBManager.em;
        if (!em.getTransaction().isActive()) { 
            em.getTransaction().begin();
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        paymentQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT p FROM Payment p");
        paymentList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : paymentQuery.getResultList();
        stationQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT s FROM Station s");
        stationList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : stationQuery.getResultList();
        appUser = Session.loginUser;
        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        paymentScrollPane = new javax.swing.JScrollPane();
        paymentTable = new javax.swing.JTable();
        jTextField1 = new javax.swing.JTextField();
        separator = new javax.swing.JSeparator();
        station = new javax.swing.JLabel();
        StationSearch = new javax.swing.JComboBox();
        epistrofi = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        Anazitisi = new javax.swing.JButton();
        apoDate = new com.toedter.calendar.JDateChooser();
        eosDate = new com.toedter.calendar.JDateChooser();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("ΙΣΤΟΡΙΚΟ ΠΛΗΡΩΜΩΝ");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText("Έως:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Αριθμός Πινακίδας:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Από:");

        jTextField2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Αριθμός Κάρτας:");

        paymentTable.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, paymentList, paymentTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cardId.id}"));
        columnBinding.setColumnName("Card Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${paymentTimestamp}"));
        columnBinding.setColumnName("Payment Timestamp");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${newBalance}"));
        columnBinding.setColumnName("New Balance");
        columnBinding.setColumnClass(java.math.BigDecimal.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        paymentScrollPane.setViewportView(paymentTable);

        jTextField1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        station.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        station.setText("ΣΤΑΘΜΟΣ");

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, stationList, StationSearch);
        bindingGroup.addBinding(jComboBoxBinding);
        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, appUser, org.jdesktop.beansbinding.ELProperty.create("${stationId}"), StationSearch, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        epistrofi.setBackground(new java.awt.Color(0, 153, 153));
        epistrofi.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        epistrofi.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Back.gif"))); // NOI18N
        epistrofi.setText("Επιστροφή");
        epistrofi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                epistrofiActionPerformed(evt);
            }
        });

        Anazitisi.setBackground(new java.awt.Color(0, 153, 153));
        Anazitisi.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        Anazitisi.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Refresh.gif"))); // NOI18N
        Anazitisi.setText("Αναζήτηση");
        Anazitisi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AnazitisiActionPerformed(evt);
            }
        });

        apoDate.setName("apoDate"); // NOI18N

        eosDate.setName("eosDate"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(separator, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jSeparator1)
                            .addComponent(paymentScrollPane)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(station)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(StationSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(jLabel3)
                                                .addGap(41, 41, 41)
                                                .addComponent(apoDate, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                        .addGap(33, 33, 33)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18)
                                                .addComponent(eosDate, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                                .addGap(0, 237, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(Anazitisi, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(epistrofi)
                                .addGap(43, 43, 43))))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(station)
                    .addComponent(StationSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel3)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel4)
                                    .addGap(3, 3, 3)))
                            .addComponent(eosDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Anazitisi))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(apoDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addComponent(separator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(paymentScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(epistrofi)
                .addGap(30, 30, 30))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField2ActionPerformed

    private void epistrofiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_epistrofiActionPerformed
        // Κλείσιμο του παραθύρου
        dispose();
    }//GEN-LAST:event_epistrofiActionPerformed

    private void AnazitisiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnazitisiActionPerformed

        try {

            String cardId = jTextField1.getText();
            String regNumber = jTextField2.getText();
            String stationId = ((Station) stationList.get(StationSearch.getSelectedIndex())).getId().toString();
            Date apo;
            try {
                Calendar calculateApo = apoDate.getCalendar();
               calculateApo.set(Calendar.HOUR_OF_DAY, 0);
                calculateApo.set(Calendar.MINUTE, 0);
                calculateApo.set(Calendar.SECOND, 0);
               calculateApo.set(Calendar.DAY_OF_YEAR,
                    calculateApo.get(Calendar.DAY_OF_YEAR)-1);
                apo = calculateApo.getTime();
            } catch(Exception ex) {
                apo = null;
            }
            Date eos;
            try {
                Calendar calculateEos = eosDate.getCalendar();
                calculateEos.set(Calendar.HOUR_OF_DAY, 0);
                calculateEos.set(Calendar.MINUTE, 0);
                calculateEos.set(Calendar.SECOND, 0);
                eos = calculateEos.getTime();
            } catch(Exception ex) {
                eos = null;
            }

            List<Payment> pList = paymentQuery.getResultList();

            for (int i = pList.size()-1; i>= 0; i--) {
                Payment pay = pList.get(i);
                boolean afairese = false;

                if (!cardId.equals("")) {
                    if (!pay.getCardId().getId().toString().equals(cardId)) {
                        afairese = true;
                                            }
                }

                if (!regNumber.equals("")) {
                    for (Vehicle h : pay.getCardId().getVehicleList()) {
                        if (!h.getRegNumber().equals(regNumber)) {
                            afairese = true;
                                                    }
                    }
                }

                if (!pay.getStationId().getId().toString().equals(stationId)) {
                    afairese = true;
                }

                if (apo != null) {
                    if (!apo.before(pay.getPaymentTimestamp())) {
                        afairese = true;
                    }
                }

                if (eos != null) {
                    if (!eos.after(pay.getPaymentTimestamp())) {
                        afairese = true;
                    }
                }

                if (afairese) {
                    pList.remove(pay);
                }

            }

            for (int i = 1; i < pList.size(); i++) {
                for (int j = 0; j < pList.size() - i; j++) {
                    if (pList.get(j).getPaymentTimestamp().before(pList.get(j+1).getPaymentTimestamp())) {
                        Payment p = pList.get(j);
                        pList.set(j, pList.get(j+1));
                        pList.set(j+1, p);
                    }
                }
            }

            paymentList.clear();
            for (Payment pay : pList) {
                paymentList.add(pay);
                
            }

        } catch(Exception ex) {
            System.out.println(ex.getMessage());
        }
    }//GEN-LAST:event_AnazitisiActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PresentPaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PresentPaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PresentPaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PresentPaymentForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PresentPaymentForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Anazitisi;
    private javax.swing.JComboBox StationSearch;
    private com.toedter.calendar.JDateChooser apoDate;
    private model.AppUser appUser;
    private com.toedter.calendar.JDateChooser eosDate;
    private javax.swing.JButton epistrofi;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private java.util.List<model.Payment> paymentList;
    private javax.persistence.Query paymentQuery;
    private javax.swing.JScrollPane paymentScrollPane;
    private javax.swing.JTable paymentTable;
    private javax.swing.JSeparator separator;
    private javax.swing.JLabel station;
    private java.util.List<model.Station> stationList;
    private javax.persistence.Query stationQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
EntityManager em;
}
